export enum SoundName {
    bgm_long = "bgm_long",
    bgm_short = "bgm_short",
    clickEffect = "clickEffect",
    gamestart = "gamestart",
    menuBgm = "menuBgm",
    removeEffect = "removeEffect",
    shuffleEffect = "shuffleEffect"
}

export  class SoundManager {
    private static _instance: SoundManager = null;

    public static get Instance(): SoundManager {
        this._instance = this._instance || new SoundManager();
        return this._instance;
    }

    private _isAllMute: boolean = false;
    private _isMusicMute: boolean = false;
    private _isEffectMute: boolean = false;
    private _soundMap: { [key: string]: cc.AudioClip } = {};

    private loadSoundClip(clipName: SoundName) {
        return new Promise((resolve, reject) => {
            cc.resources.load("sounds/" + clipName, cc.AudioClip, (err, clip: cc.AudioClip) => {
                if (err) {
                    console.error(clipName + "is load err");
                } else {
                    resolve(clip);
                }
            })
        })
    }

    public setSoundMute(bool: boolean) {
        this._isAllMute = bool;
    }

    public setMusicMute(bool: boolean) {
        this._isMusicMute = bool;
        if (bool) {
            cc.audioEngine.pauseMusic();
        } else {
            cc.audioEngine.resumeMusic();
        }
    }

    public setEffectMute(bool: boolean) {
        this._isEffectMute = bool;
        if (bool) {
            cc.audioEngine.stopAllEffects();
        }
    }

    //******************以下背景音乐模块******************************* */
    public playMusic(clipName: SoundName, volume: number = 0.5, isLoop: boolean = true) {
        if (this._isAllMute || this._isMusicMute) return;
        if (this._soundMap[clipName]) {
            cc.audioEngine.playMusic(this._soundMap[clipName], isLoop);
        } else {
            this.loadSoundClip(clipName).then((clip: cc.AudioClip) => {
                cc.audioEngine.playMusic(clip, isLoop);
                this._soundMap[clip.name] = clip;
            })
        }
        cc.audioEngine.setMusicVolume(volume);
    }

    public setMusicVolume(volume: number = 0.5) {
        cc.audioEngine.setMusicVolume(volume);
    }

    //******************以下音效模块******************************* */
    public playEffect(clipName: SoundName, volume: number = 0.5, isLoop: boolean = false) {
        if (this._isAllMute || this._isEffectMute) return;
        if (this._soundMap[clipName]) {
            cc.audioEngine.playEffect(this._soundMap[clipName], isLoop);
        } else {
            this.loadSoundClip(clipName).then((clip: cc.AudioClip) => {
                cc.audioEngine.playEffect(clip, isLoop);
                this._soundMap[clip.name] = clip;
            })
        }
        cc.audioEngine.setEffectsVolume(volume);
    }

    public setEffectsVolume(volume: number = 0.5) {
        cc.audioEngine.setEffectsVolume(volume);
    }

}